﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UFramework.Tools;
using UnityEngine.Audio;
using System;
public class AudioManger : UnitySingleton<AudioManger>
{
    //组对应的音量
    private Dictionary<AudioGroup, float> volumeDic = new Dictionary<AudioGroup, float>();

    //音量改变的事件
    public event Action<AudioGroup, float> OnVolumeChange;

    //读取保存的音量,如果未保存默认值是0.5f
    protected override void Init()
    {
        string[] groups = Enum.GetNames(typeof(AudioGroup));
        foreach (var item in groups)
        {
            AudioGroup group = (AudioGroup)Enum.Parse(typeof(AudioGroup), item);
            volumeDic[group] = PlayerPrefs.GetFloat("AudioVolume_" + item, 0.5f);
        }
    }

    //保存设置的音量
    private void OnApplicationQuit()
    {
        foreach (var item in volumeDic)
        {
            PlayerPrefs.SetFloat("AudioVolume_" + item.Key, item.Value);
        }
    }
    public float GetVolume(AudioGroup group)
    {
        return volumeDic[group];
    }

    public void SetVolume(AudioGroup group, float volume)
    {
        volumeDic[group] = volume;
        //产生一个事件
        OnVolumeChange?.Invoke(group, volume);
    }

    public void PlaySond(AudioClip audioClip, AudioGroup group)
    {
        AudioPlayer player = GetPlayer();
        player.Play(audioClip, group);
    }

    //后面修改成缓存机制
    private static AudioPlayer GetPlayer()
    {
        AudioPlayer player = new GameObject("AudioPlayer").AddComponent<AudioPlayer>();
        return player;
    }
}